from typing import List, Dict
from zhipuai import ZhipuAI

MODEL = "glm-4-plus"
client = ZhipuAI(api_key='652056ee12c005f36b61ba8df67274b2.US6dlqS8ckjtuQv3')

class ComparisonAgent:
    def compare_methods(self, summaries: List[Dict], papers: List[Dict]) -> Dict[str, str]:
        """
        比较智能体：比较论文中的方法和途径，并生成对比表格
        :param summaries: 论文摘要列表，每个元素包含title、summary和key_findings
        :param papers: 论文原文列表，用于生成详细对比表格
        :return: 返回比较结果和对比表格
        """
        try:
            # 准备论文摘要文本
            summary_text = ""
            for i, summary in enumerate(summaries):
                summary_text += f"Paper {i+1}:\n"
                summary_text += f"Title: {summary['title']}\n"
                summary_text += f"Summary: {summary['summary']}\n"
                summary_text += f"Key Findings: {', '.join(summary['key_findings'])}\n\n"

            # 生成综合比较分析
            comparison_prompt = f"""As an academic research expert, please analyze the following research papers and provide a comprehensive methodological comparison:

            1. A systematic analysis of research methods that:
               - Evaluates both qualitative and quantitative methodologies used
               - Assesses the appropriateness of each method for the research questions
               - Compares data collection and analysis approaches
               - Examines the validity and reliability of methods
               - Identifies methodological strengths and limitations
               - Highlights innovative approaches and their effectiveness
               - Provides evidence-based conclusions

            2. A detailed comparison table that includes:
               - Research paradigm (qualitative/quantitative/mixed)
               - Specific methodologies employed
               - Data collection and analysis techniques
               - Key innovations in methodology
               - Performance metrics and outcomes
               - Methodological strengths and limitations

            Format your response as:
            ANALYSIS:
            [Your comprehensive comparison]

            TABLE:
            | Method | Innovation | Performance | Notes |
            |--------|------------|-------------|--------|
            [Your detailed comparison table]

            Papers to analyze:
            {summary_text}"""

            response = client.chat.completions.create(
                model=MODEL,
                messages=[{"role": "system", "content": "You are a research methodology comparison expert."}, 
                          {"role": "user", "content": comparison_prompt}],
                temperature=0.2
            )
            
            content = response.choices[0].message.content
            
            # 解析响应内容
            parts = content.split("\nTABLE:")
            analysis = parts[0].replace("ANALYSIS:", "").strip()
            table = parts[1].strip() if len(parts) > 1 else "| Method | Innovation | Performance | Notes |\n|--------|------------|-------------|--------|\n| - | - | - | - |"
            
            return {
                "comparison": analysis,
                "table": table
            }
            
        except Exception as e:
            print(f"生成比较分析失败: {str(e)}")
            return {
                "comparison": "比较分析生成失败",
                "table": "| Method | Innovation | Performance | Notes |\n|--------|------------|-------------|--------|\n| - | - | - | - |"
            }
